﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Web.Configuration;

namespace HoaDon
{
	public partial class SubAcountManagement : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			if (!IsPostBack)
			{
				BindData();
				lbError.Text = "";
			}
		}

		private void BindData()
		{

			DataTable dt = new DataTable();
			dt = SqlEXEC.GetData(WebConfigurationManager.ConnectionStrings["proxyconn"].ConnectionString, "SELECT * FROM Userinfo WHERE ParentUser = '" + User.Identity.Name.ToUpper() + "'");

			gdvAccount.DataSource = dt;
			gdvAccount.DataBind();

		}

		protected void EditDM(object sender, GridViewEditEventArgs e)
		{
			gdvAccount.EditIndex = e.NewEditIndex;
			BindData();
			lbError.Text = "";
		}
		protected void CancelEditDM(object sender, GridViewCancelEditEventArgs e)
		{
			gdvAccount.EditIndex = -1;
			BindData();
			lbError.Text = "";
		}

		protected void OnPaging(object sender, GridViewPageEventArgs e)
		{
			BindData();
			gdvAccount.PageIndex = e.NewPageIndex;
			gdvAccount.DataBind();
			lbError.Text = "";
		}

		protected void UpdateDM(object sender, GridViewUpdateEventArgs e)
		{
			string id = ((Label)gdvAccount.Rows[e.RowIndex].FindControl("UserID")).Text;
			bool b_status = ((CheckBox)gdvAccount.Rows[e.RowIndex].FindControl("ckStatus")).Checked;
			string status = "";
			if (b_status == true)
				status = "1";
			else
				status = "0";
			try
			{
				string sCommand = "UPDATE Userinfo SET Status = '" + status + "' WHERE UserID = '" + id + "'";
				SqlEXEC.ExecCommand(WebConfigurationManager.ConnectionStrings["proxyconn"].ConnectionString, sCommand);
				gdvAccount.EditIndex = -1;
				BindData();
				lbError.Text = "";
			}
			catch (Exception ex)
			{
				lbError.Text = "Xảy ra lỗi khi cập nhật dữ liệu";
				gdvAccount.EditIndex = -1;
				BindData();
			}
		}

		protected void DeleteDM(object sender, EventArgs e)
		{
			Button bt = (Button)sender;
			try
			{
				SqlEXEC.ExecCommand(WebConfigurationManager.ConnectionStrings["proxyconn"].ConnectionString, "DELETE FROM Userinfo WHERE UserID = '" + bt.CommandArgument + "'");
			}
			catch (Exception ex)
			{
				lbError.Text = "Đã phát sinh dữ liệu không thể xóa";
			}
			BindData();
		}

		protected void ViewSubAccount(object sender, GridViewSelectEventArgs e)
		{
			string id = ((Label)gdvAccount.Rows[e.NewSelectedIndex].FindControl("UserID")).Text;
			string name = ((Label)gdvAccount.Rows[e.NewSelectedIndex].FindControl("UserName")).Text;
			Session["SubAccountID"] = id;
			Response.Redirect("~\\ChangeSubUserInfo.aspx");
		}
	}
}
